<?php

namespace app\admin\controller\sales\report;

use app\common\controller\Backend;
use app\common\model\customer\Customer;
use app\common\model\goods\Goods;
use app\common\model\sales\ChangeGoods;
use app\common\model\sales\CheckoutGoods;
use think\Db;
use app\common\model\goods\GoodsHouseStock;
use think\Exception;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Groupranking extends Backend
{
    
    /**
     * Change模型对象
     * @var \app\common\model\sales\Change
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\sales\Change();

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $start_time = date('Y-m-01', strtotime(date("Y-m-d")));
//        $end_time = time();
        if ($this->request->isAjax())
        {

            $filter = json_decode($this->request->get('filter'),true);
            $params = [];
            if(!empty($filter)){
                if(isset($filter['createtime'])){
                    $arr = explode(' - ',$filter['createtime']);
                    $start_time = isset($arr[0])?strtotime($arr[0]):$start_time;
                    $end_time = isset($arr[1])?strtotime($arr[1]):time();
                    $params['createtime'] = array('between time',[$start_time,$end_time]);
                }
            }

            $total = 0;
            $list = [];
            $group = Db::name('auth_group')->where(array('pid'=>1))->select();
            $total = count($group);
            foreach ($group as $v){
                //获取该部门下所有的小部门ID
                $gids = Db::name('auth_group')->where(array('gid'=>$v['id']))->column('id');


                $gids[count($gids)] = $v['id'];


                $sale_price = 0;
                $factory_price = 0;
                //销售数量
                $sale_num = Db::name('sales_checkout_goods')->where($params)->where(array('status'=>array('>',0)))->where(array('group_id'=>array('in',$gids)))->sum('goods_num');
                if($sale_num){
                    //销售金额
                    $sale_price = Db::name('sales_checkout_goods')->where($params)->where(array('status'=>array('>',0)))->where(array('group_id'=>array('in',$gids)))->sum('sale_price*goods_num');
                }
                $factory_num = Db::name('factory_sales_goods')->where($params)->where(array('status'=>array('>',0)))->where(array('group_id'=>array('in',$gids)))->sum('goods_num');
                if($factory_num){
                    //销售金额
                    $factory_price = Db::name('factory_sales_goods')->where($params)->where(array('status'=>array('>',0)))->where(array('group_id'=>array('in',$gids)))->sum('sale_price*goods_num');
                }
                $all_num = $sale_num+$factory_num;


                if(!empty($all_num)){
                    $all_price = bcadd($sale_price,$factory_price,2);
                    //销售单价
                    $sale_money = bcdiv($all_price,$all_num,2);
                    //价税合计
//                $ht_price = Db::name('sales_checkout_goods')->where(array('group_id'=>array('in',$gids)))->sum('ht_price*goods_num');
                    $actual_cost1 = Db::name('sales_checkout')->where($params)->where(array('status'=>array('<',5)))->where(array('group_id'=>array('in',$gids)))->sum('actual_cost');
                    $actual_cost2 = Db::name('factory_sales')->where($params)->where(array('status'=>array('<',6)))->where(array('group_id'=>array('in',$gids)))->sum('actual_cost');
                    $actual_cost = bcadd($actual_cost1,$actual_cost2,2);
                    //税额
                    $tax_price = bcsub($actual_cost,$all_price,2);
                    //成本
                    $cost1 = Db::name('sales_checkout_goods')->where($params)->where(array('status'=>array('>',0)))->where(array('group_id'=>array('in',$gids)))->sum('costPrice*goods_num');
                    $cost2 = Db::name('factory_sales_goods')->where($params)->where(array('status'=>array('>',0)))->where(array('group_id'=>array('in',$gids)))->sum('unit_price*goods_num');

                    $cost = bcadd($cost1,$cost2,2);
                    //单件成本
                    $onecost = bcdiv ($cost,$all_num,2);
                    //毛利
                    $profit = $all_price-$cost;
                    //毛利率
                    $profit_margin = $profit/$all_price;

                }else{
                    $all_price = 0;
                    $sale_money = 0;
                    $actual_cost = 0;
                    $tax_price = 0;
                    $cost = 0;
                    $onecost = 0;
                    $profit = 0;
                    $profit_margin = 0;
                }



                //第一种：利用round()对浮点数进行四舍五入
//                echo round($num,2); //10.46
                //第二种：利用sprintf格式化字符串
//                $format_num = sprintf("%.2f",$num);

                $list[] = array(
                    'sale_price'=> round($all_price,2),
                    'sale_num'=>   round($all_num,2),
                    'actual_cost'=>round($actual_cost,2),
                    'tax_price'=>  round($tax_price,2),
                    'cost'=>       round($cost,2),
                    'sale_money'=> round($sale_money,2),
                    'onecost'=>    round($onecost,2),
                    'profit'=>     round($profit,2),
                    'profit_margin'=>round($profit_margin,2)*100 .'%',
                    'name'=>$v['name'],
                );


//                dump($sale_num);
//                dump($sale_price);
////                dump($ht_price);
//                dump($actual_cost);
                //出库单
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $this->assign('start_time',$start_time);
//        $this->assign('end_time',$end_time);
        return $this->view->fetch();
    }

}
